﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BLL;
namespace DAL
{
    public class DALChiTietDonHang
    {
        //them chi tiet don hang
        public static string Add(BLLChiTietDonHang ctdh)
        {
            TMDTDataContext tmdt = new TMDTDataContext();
            ChiTietDonHang d = new ChiTietDonHang();
          //  d.IDChiTietDonHang = ctdh.Idchitiet;
            d.IDSanPham = ctdh.Idsanpham;
            d.IDDonHang =  Convert.ToInt32(ctdh.Iddonhang);
            d.SoLuong = ctdh.Soluong;
            d.DonGia = ctdh.Dongia;
            d.ThanhTien = ctdh.Thanhtien;
            DALCommon.TMDTDB.ChiTietDonHangs.InsertOnSubmit(d);
            DALCommon.TMDTDB.SubmitChanges();
            return d.IDChiTietDonHang.ToString();
        }
        //lay chi tiet=id
        public static List<BLLChiTietDonHang> GetById(BLLChiTietDonHang ct)
        {
            var result = from chitiet in DALCommon.TMDTDB.ChiTietDonHangs
                         from sanpham in DALCommon.TMDTDB.SanPhams
                         where chitiet.IDDonHang.ToString()== ct.Iddonhang &&chitiet.IDSanPham==sanpham.IDSanPham
                         select
                         new BLLChiTietDonHang(chitiet.IDChiTietDonHang.ToString(),chitiet.IDSanPham.ToString(),chitiet.IDSanPham.ToString(),Convert.ToInt32(chitiet.SoLuong),chitiet.DonGia,chitiet.ThanhTien,sanpham.TenSanPham,sanpham.KickCo,sanpham.Mau);
            return result.ToList<BLLChiTietDonHang>();
        }
        //xoa chi tiet khi xoa san pham
        public static string DeletebySanpham(BLLChiTietDonHang chitiet)
        {
            try
            {
                var result = from cthd in DALCommon.TMDTDB.ChiTietDonHangs
                             where cthd.IDSanPham==chitiet.Idsanpham
                             select cthd;
                //ChiTietDonHang ct = DALCommon.TMDTDB.ChiTietDonHangs.Single<ChiTietDonHang>(n => n.IDSanPham == chitiet.Idsanpham);
                DALCommon.TMDTDB.ChiTietDonHangs.DeleteAllOnSubmit(result);
                DALCommon.TMDTDB.SubmitChanges();
            }
            catch
            { }
            return chitiet.Idchitiet;
        }

        //xoa chi tiet khi xoa don hang
        public static string DeletebyDonhang(BLLChiTietDonHang chitiet)
        {

                var result = from cthd in DALCommon.TMDTDB.ChiTietDonHangs
                             where cthd.IDDonHang.ToString() == chitiet.Iddonhang
                             select cthd;
                //ChiTietDonHang ct = DALCommon.TMDTDB.ChiTietDonHangs.Single<ChiTietDonHang>(n => n.IDDonHang.ToString() == chitiet.Iddonhang);
                DALCommon.TMDTDB.ChiTietDonHangs.DeleteAllOnSubmit(result);
                DALCommon.TMDTDB.SubmitChanges();

            return chitiet.Idchitiet;
        }
    }
}
